import axios, {AxiosResponse} from 'axios';
import {notification, message} from 'antd';

// 创建Axios实例
const instance = axios.create({
    baseURL: "/api", // 根据实际情况修改baseURL
    timeout: 5000 // 设置超时时间
});

// 打开通知函数
const openNotification = (type: 'success' | 'error', message: string, description: string) => {
    notification[type]({
        message,
        description,
        duration: 2,
    });
};

// 添加请求拦截器
instance.interceptors.request.use(config => {
    // 在发送请求之前做些什么
    message.loading('Loading...');
    return config;
}, error => {
    // 对请求错误做些什么
    message.error('Request Error');
    return Promise.reject(error);
});

// 添加响应拦截器
instance.interceptors.response.use(response => {
    // 对响应数据做点什么
    message.destroy(); // 清除loading提示

    console.log('response', response)
    if (response.request.responseURL.includes("auth/login")) {
        if (response.data.code == 200) {
            window.location.href = "/main"
        }
    }
    if (response.request.responseURL.includes("/email/verifyEmailCode")) {
        if (response.data.code == 200) {
            window.location.href = "/main"
        }
    }
    if (response.data.code == 200) {
        // message.success('Request Successful');
    }
    return response;
}, error => {
    // 对响应错误做点什么
    message.destroy(); // 清除loading提示
    console.log('error', error)
    if (axios.isAxiosError(error)) {
        const errorMessage = error.message || 'Unknown error';
        openNotification('error', 'Error', errorMessage);
    } else {
        openNotification('error', 'Error', 'An unexpected error occurred');
    }
    if (error?.response?.data?.code == 401) {
        window.location.href = "/login"
    }

    return Promise.reject(error);
});

// GET请求封装
export const get = async <T>(url: string, params?: object): Promise<T> => {
    const response: AxiosResponse<T> = await instance.get(url, {params});
    return response.data;
};

// POST请求封装
export const post = async <T>(url: string, data?: object): Promise<T> => {
    const response: AxiosResponse<T> = await instance.post(url, data);
    return response.data;
};

// 文件上传封装
export const upload = async <T>(url: string, file: File): Promise<T> => {
    const formData = new FormData();
    formData.append('file', file);
    const response: AxiosResponse<T> = await instance.post(url, formData, {
        headers: {
            'Content-Type': 'multipart/form-data',
        },
    });
    return response.data;
};
